/*
 * Created on 2004-02-26
 */
package org.opencube.oms.test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Properties;

/**
 * @author <a href="mailto:maciek@fingo.pl">FINGO - Maciej Mroczko</a>
 * TODO: comment
 */
public class DBState
{
	/* The states of the single tables */
	private HashMap tableStates = new HashMap();
	
	/**
	 */
	public DBState()
	{
	}
	
	public DBState( File file ) throws FileNotFoundException, IOException
	{
		load( new FileInputStream( file ) );
	}
	/**
	 * @param tableName
	 * @return
	 */
	public TableState getTableState( String tableName )
	{
		return (TableState) tableStates.get( tableName ); 
	}
	
	/**
	 * 
	 * @param tableState
	 */
	public void addTableState( TableState tableState )
	{
		tableStates.put( tableState.getTableName(), tableState );
	}

	/**
	 * @return
	 */
	public TableState[] getTableStates()
	{
		return (TableState[]) tableStates.values().toArray( new TableState[ tableStates.values().size() ] );
	}
	
	/**
	 * @param is
	 */
	public void load( InputStream is ) throws IOException
	{
		Properties props = new Properties();
		props.load( is );
		Iterator it = props.keySet().iterator();
		tableStates.clear();
		while( it.hasNext() )
		{
			String tableName = (String) it.next();
			String value = props.getProperty( tableName );
			try
			{
				addTableState( new TableState( tableName, Integer.parseInt( value ) ) );
			}
			catch( NumberFormatException e )
			{
				System.out.println( "warning: the value for table " + tableName + " is not valid integer value: " + value );
			}
		}
	}
	
	/**
	 * @param os
	 * @param comment
	 * @throws IOException
	 */
	public void store( OutputStream os, String comment )
	throws IOException
	{
		Properties props = new Properties();
		Iterator it = tableStates.values().iterator();
		while( it.hasNext() )
		{
			TableState ts = (TableState) it.next();
			props.setProperty( ts.getTableName(), String.valueOf( ts.hashCode() ) );
		}
		props.store( os, comment );
	}

	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#hashCode()
	 */
	public int hashCode()
	{
		int result = 0;
		Iterator it = tableStates.values().iterator();
		while( it.hasNext() ) 
		{
			result += it.next().hashCode();
		}
		return result;
	} 
	
	/*
	 * (non-Javadoc)
	 * @see java.lang.Object#equals(java.lang.Object)
	 */
	public boolean equals( Object o )
	{
		if( o instanceof DBState )
		{
			return ( (DBState) o ).hashCode() == this.hashCode();
		}
		return false;
	}
}
